<template>
    <div class="login">
        <el-form :model="user" :rules="formRules" ref="formRef">
            <el-form-item label="用户号" prop="number">
                <el-input v-model="user.number" placeholder="请输入用户号"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="user.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login(formRef)">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import http from '../utils/http'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
let router = useRouter()
import { ElMessage, ElMessageBox } from 'element-plus'
//定义对象接受用户表单输入信息
//ref()方法创建响应式数据，注意在js里要访问ref返回的响应式变量，需要.value
//account.value.account

let user = ref({
    number: '',
    password: ''
})
//定义表单验证规则
let formRef = ref(null)
let formRules = ref({
    number: [
        { required: true, message: '请输入用户号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
})
//定义当用户点击登陆按钮时，执行login函数
async function login(formRef) {
    formRef.validate(async function (valid){
        if (valid) {
            let resp = await http.post('/user/login', user.value)
            let code = resp.code
            if (code == 200) {        
            // 1.将用户信息缓存到本地
            localStorage.setItem('user', JSON.stringify(resp.data))
            // 2.登陆成功，跳转到后端
            router.push('/')
            } else if (code == 500) {
            // 登陆失败
            ElMessageBox.alert('用户号或密码错误', '登录失败', {
            confirmButtonText: 'OK'
           })
         }
        }
    })
}
</script>

<style lang="css" scoped>
.login {
    width: 300px;
    margin: 0 auto;
}
</style>